import { Component, ViewChild, ElementRef, OnInit, Input } from '@angular/core';
import { FileUploader, FileItem, ParsedResponseHeaders } from 'ng2-file-upload';
import { IBizEnvironment } from '@env/IBizEnvironment';
import { IBizNotification } from '@ibizsys/util/IBizNotification';
import { NzModalSubject } from 'ng-zorro-antd';

@Component({
    selector: 'app-ibiz-importdata-view',
    templateUrl: './ibiz-importdata-view.component.html',
    styleUrls: ['./ibiz-importdata-view.component.less']
})
export class IBizImportdataViewComponent implements OnInit {

    /**
	 * 上传插件对象
	 * 
	 * @type {FileUploader}
	 * @memberof IBizFileUploadComponent
	 */
    public uploader: FileUploader;

    /**
	 * 已上传文件对象集合
	 * 
	 * @type {any[]}
	 * @memberof IBizFileUploadComponent
	 */
    public files: any[] = [];

    /**
     * 是否成功上传有文件
     * 
     * @memberof IBizImportdataViewComponent
     */
    public $ret = false;

    /**
     * 上传状态
     *
     * @memberof IBizImportdataViewComponent
     */
    public updateState = true;

    /**
     * 上传中个数统计
     *
     * @memberof IBizImportdataViewComponent
     */
    public num = 0;

    /**
	 * 实体名称
	 * 
	 * @type {string}
	 * @memberof IBizImportdataViewComponent
	 */
    @Input()
    dename: string;

    @ViewChild('fileUpload')
    fileUpload: ElementRef;

    constructor(
        private iBizNotification: IBizNotification,
        private nzModalSubject: NzModalSubject
    ) {
    }

    ngOnInit() {
        let url = IBizEnvironment.UploadDEData + '?srfdeid=' + this.dename;
        url = (IBizEnvironment.LocalDeve ? '' : '..') + url;
        this.uploader = new FileUploader({
            url: url,
            autoUpload: false,
            allowedFileType: ['xls'],
            itemAlias: 'updateState'
        });
        this.uploader.onSuccessItem = (item, response, status, headers) => {
            this.successItem(item, response, status, headers);
        };
        this.uploader.onErrorItem = (item, response, status, headers) => {
            this.successItem(item, response, status, headers);
        };
        this.uploader.onAfterAddingAll = (fileItems) => {
            this.files.push(...fileItems);
        };

        this.nzModalSubject.on('onDestroy', () => {
            this.nzModalSubject.next({ret: this.$ret});
        });
    }

    /**
	 * 上传文件成功返回
	 * 
	 * @param {FileItem} item 
	 * @param {string} response 
	 * @param {number} status 
	 * @param {ParsedResponseHeaders} headers 
	 * @returns {*} 
	 * @memberof IBizFileUploadComponent
	 */
    public successItem(item: FileItem, response: string, status: number, headers: ParsedResponseHeaders): any {
        this.num--;
        if (this.num === 0) {
            this.updateState = true;
        }
        let res: any = JSON.parse(response);
        if (res && res.ret === 0) {
            this.$ret = true;
            item['processInfo'] = res.processinfo;
            item['errorFileId'] = res.errorfileid;
        } else {
            this.iBizNotification.error('错误', res.errorMessage);
        }
    }

    /**
	 * 触发上传功能
	 * 
	 * @memberof IBizFileUploadComponent
	 */
    public importFile(): void {
        this.fileUpload.nativeElement.click();
    }

    /**
     * 下载导入数据模板
     * 
     * @memberof IBizImportdataViewComponent
     */
    public downDataExcel(): void {
        if (!Object.is(this.dename, '')) {
            let url = IBizEnvironment.ExportExcel + '?srfdeid=' + this.dename;
            url = (IBizEnvironment.LocalDeve ? '' : '..') + url;
            window.open(url);
        }
    }

    /**
     * 开始上传
     * 
     * @memberof IBizImportdataViewComponent
     */
    public uploadExcel(): void {
        this.num = 0;
        this.updateState = false;
        this.files.forEach((file: FileItem) => {
            if (file.isUploaded) {
                return;
            }
            this.num++;
            file.upload();
        });
    }

    /**
     * 生成下载导入失败文件地址
     * 
     * @param {FileItem} file 
     * @returns {string} 
     * @memberof IBizImportdataViewComponent
     */
    public appendPath(file: FileItem): string {
        let url = IBizEnvironment.ExportFile + '?FILEID=' + file['errorFileId'];
        url = (IBizEnvironment.LocalDeve ? '' : '..') + url;
        return url;
    }
}
